<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!--  缺点：-->
    <!-- 1）只支持get -->
    <!-- 2）我们传递的回调必须是一个全局方法，我们都知道要尽量减少全局的方法。 -->
    <!-- 3）需要加入一些参数校验，确保接口可以正常执行。 -->
    <!-- 4)  XXS攻击（注入恶意指令代码到网页）  -->
    <!-- <script src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=b&cb=show"></script> -->
    <script>
      function jsonp({ url, params, cb }) {
        return new Promise((resolve, reject) => {
          window[cb] = function (data) {
            resolve(data);
            document.body.removeChild(script);
          };
          params = { ...params, cb };
          let arr = [];
          for (key in params) {
            arr.push(`${key}=${params[key]}`);
          }
          let script = document.createElement("script");
          script.src = `${url}?${arr.join(`&`)}`;
          document.body.appendChild(script);
        });
      }
      jsonp({
        url: "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su",
        params: { wd: "b" },
        cb: "show",
      }).then((data) => {
        console.log(data);
      });
    </script>
  </body>
</html>
